<template>
	<view>
		<view class="top flex flex-direction align-center justify-center">
			<text>支付金额</text>
			<text>￥{{paymentList.order_amount}}</text>
		</view>
		<view class="title flex align-center">
			选择支付方式
		</view>
		<radio-group class="block" @change="RadioChange">
			<view class="list flex align-center justify-between">
				<view class="flex align-center">
					<!-- 	<image src="/static/c3.png"></image> -->
					<image src="/static/c4.png"></image>
					<text>余额支付</text>
				</view>
				<radio class='radio' value="B"></radio>
			</view>
			<!-- #ifdef MP-WEIXIN -->
			<view class="list flex align-center justify-between">
				<view class="flex align-center">
					<image src="/static/c4.png"></image>
					<text>微信</text>
				</view>
				<radio class='radio' checked="true" value="A"></radio>
			</view>
			<!-- #endif -->
			<!-- #ifdef MP-ALIPAY -->
			<view class="list flex align-center justify-between">
				<view class="flex align-center">
					<image src="/static/c3.png"></image>
					<text>支付宝</text>
				</view>
				<radio class='radio' checked="true" value="A"></radio>
			</view>
			<!-- #endif -->

			<view class="list flex align-center justify-between">
				<view class="flex align-center">
					<image src="/static/c2.png"></image>
					<text>月结</text>
				</view>
				<radio class='radio' value="C"></radio>
			</view>
			<view class="list flex align-center justify-between">
				<view class="flex align-center">
					<image src="/static/c1.png"></image>
					<text>货到付款</text>
				</view>
				<radio class='radio' value="D"></radio>
			</view>
		</radio-group>
		<!-- #ifdef MP-WEIXIN -->
		<view class="botbtn flex align-center justify-center">
			<view @click="showPop" style="border: 0;">立即支付</view>
		</view>
		<!-- #endif -->
		<!-- #ifdef MP-ALIPAY -->
		<view class="botbtn flex align-center justify-center">
			<button type="primary" @click="getAuthCode" style="border: 0;">立即支付</button>
		</view>
		<!-- #endif -->
		<view v-if="isShowPop" class="popup flex align-center justify-center">
			<view class="popup-con flex flex-direction align-center justify-center">
				<image src="/static/c5.png"></image>
				<text>支付成功</text>
				<text>您已付款成功，您可在</text>
				<text>个人中心—我的订单中关注订单进度</text>
				<view class="popup-btn flex align-center justify-between">
					<view @tap='toIndex'>返回首页</view>
					<view @tap='toMain'>查看订单进度</view>
				</view>
				<text @click="close" class="close lg text-gray cuIcon-roundclose"></text>
			</view>
		</view>
	</view>
</template>

<script>
	var api = require('@/components/api.js');
	export default {
		data() {
			return {
				isShowPop: false,
				order: {
					order_no: '',
					order_id: '',
					order_type: ''
				},
				openId: '',
				payWay: 'A',
				paymentList: '',
				// #ifdef MP-ALIPAY
				canIUseAuthButton: my.canIUse('button.open-type.getAuthorize'),
				// #endif
				authCode: ''
			}
		},
		onLoad(opt) {
			if (opt.key) {
				this.order = JSON.parse(opt.key)
			}
			this.loadPaymentList()
			this.getOpenid()
		},
		methods: {
			getAuthCode() {
				// #ifdef MP-ALIPAY
				let _this = this
				if (_this.payWay == 'A') {
					my.getAuthCode({
						scopes: 'auth_base',
						success: (res) => {
							console.log('getAuthCode res', res)
							_this.authCode = res.authCode
							_this.payWx();
						},
						fail: (err) => {
							console.log('授权错误', err)
						}
					});
				} else {
					_this.showPop();
				}
				// #endif
			},
			onGetAuthorize() {
				// #ifdef MP-ALIPAY
				let _this = this
				my.getOpenUserInfo({
					fail: (res) => {
						console.log('授权失败:', res);
					},
					success: (res) => {
						let userInfo = JSON.parse(res.response).response // 以下方的报文格式解析两层 response
						console.log('userInfo', userInfo)
						_this.showPop();
					}
				});
				// #endif
			},
			onAuthError(res) {
				console.log('授权失败:', res);
			},
			loadPaymentList: function() {
				api.get({
					url: 'Order/GetPaymentList',
					data: {
						order_no: this.order.order_no
					},
					success: data => {
						console.info('loadPaymentList' + JSON.stringify(data))
						if (data.ErrCode == 0) {
							this.paymentList = data.Response
						}
					}
				})
			},
			payAmountOrderAmountPay: function() {
				api.get({
					url: 'Order/GetOrderAmountPay',
					data: {
						order_no: this.order.order_no
					},
					success: data => {
						console.info('payAmountOrderAmountPay' + JSON.stringify(data))
						if (data.ErrCode == 0) {
							this.isShowPop = true
						}
					}
				})
			},
			getOpenid: function() {
				let _this = this
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						console.log(JSON.stringify(loginRes))
						let code = loginRes.code;
						//2.将用户登录code传递到后台置换用户SessionKey、OpenId等信息
						api.get({
							url: 'User/GetOnLogin',
							data: {
								code: code
							},
							success: (res) => {
								console.log('code:' + JSON.stringify(res))
								if (res.ErrCode == 0) {
									_this.openId = JSON.parse(res.Response).openid
									console.log('openId:' + _this.openId)
								}
							}
						});
					},
				});

			},
			payMWx() {
				console.log('this.openId:' + this.openId)
				api.get({
					url: 'Payment/GetAll',
					data: {
						openid: this.openId,
						amount: 1.0
					},
					success: data => {
						console.info('payMWX:' + JSON.stringify(data))
						if (data.ErrCode == 0) {}
						uni.showToast({
							title: '成功'
						})
					},

				});
			},
			payWx() {
				let _this = this

				console.log(_this.order);
				// #ifdef MP-WEIXIN || H5
				let paytype = 'wechat';
				// #endif
				// #ifdef MP-ALIPAY
				let buyer_id = uni.getStorageSync('buyer_id')
				api.post({
						// #endif
						// #ifdef MP-WEIXIN || H5
						api.get({
							// #endif	
							// #ifdef MP-ALIPAY
							url: 'Alipay/Pay?pay_order_no=' + _this.order.order_no + '&pay_order_amount=' + this
								.paymentList.order_amount + '&buyer_id=' + buyer_id,
							// #endif
							// #ifdef MP-WEIXIN || H5
							url: 'Order/GetUnifiedOrderResult',
							// #endif
							data: {
								// user_id: uni.getStorageSync('user').user_id,

								// #ifdef MP-WEIXIN || H5
								paytype: paytype,
								openid: this.openId,
								order_id: _this.order.order_id
								// #endif
								// #ifdef MP-ALIPAY
								//userCode: _this.authCode,
								//orderNo:_this.order.order_no
								// #endif
							},
							success: data => {
								console.info('payWx:' + JSON.stringify(data))

								if (data.ErrCode == 0) {
									// #ifdef MP-WEIXIN  || H5
									var dataTemp = JSON.parse(data.Response.param)
									console.info('payWx package:' + dataTemp.package)
									console.info('payWx dataTemp:' + JSON.stringify(dataTemp))

									uni.requestPayment({
										provider: 'wxpay',
										nonceStr: dataTemp.nonceStr, //　　随机字符串　　　　【字符串】
										package: dataTemp
											.package, //　　统一下单接口 必须加前缀：prepay_id=xxxxxxxx  【字符串】
										paySign: dataTemp.paySign, //　　签名     【字符串】
										signType: dataTemp.signType, //　　签名算法  【字符串】
										timeStamp: dataTemp.timeStamp, //　　时间戳   【字符串】
										// total_fee:data.Response.total_fee,
										success: function(res) {
											console.log('payWx success:' + JSON.stringify(res));
											_this.isShowPop = true
										},
										fail: function(err) {
											uni.showToast({
												title: '支付失败'
											})
											console.log('payWx 支付失败')
											console.log('payWx fail:' + JSON.stringify(err));
										},
										complete: function(res) {
											console.log('payWx---complete' + JSON.stringify(res))
										}
									});
									// #endif
									// #ifdef MP-ALIPAY

									my.tradePay({
										// 调用资金冻结接口（alipay.fund.auth.order.app.freeze），获取支付宝预授权参数
										tradeNO: data.Response.TradeNo,
										success: (res) => {
											if (res.resultCode == 9000) {
												_this.isShowPop = true
											} else {
												uni.showToast({
													title: '支付失败'
												})
											}
										},
										fail: (res) => {
											uni.showToast({
												title: '支付失败'
											})
											/*my.alert({
							    content: JSON.stringify(res),
								});*/
										}
									});

									// #endif
								} //if

							}
						})
					},
					/*
					 ** randomWord 产生任意长度随机字母数字组合
					 ** randomFlag 是否任意长度 min 任意长度最小位[固定位数] max 任意长度最大位
					 ** 
					 ** 生成6—12位随机字符串 ：randomWord(true,6,12)
					 ** 生成随机的6位字符串 ：	randomWord(false,6) 
					 */

					randomWord: function(randomFlag, min, max) {
						let str = "",
							range = min,
							arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
								'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
								'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
								'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
								'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '-'
							];

						if (randomFlag) {
							range = Math.round(Math.random() * (max - min)) + min; // 任意长度
						}
						for (let i = 0; i < range; i++) {
							var pos = Math.round(Math.random() * (arr.length - 1));
							str += arr[pos];
						}
						return str;
					},
					toIndex: function() {
						uni.switchTab({
							url: '/pages/index/index'
						})
					},
					toMain: function() {
						uni.navigateTo({
							url: '/module/my/myOrder/myOrder'
						})
					},
					showPop: function() {
						// this.isShowPop = true
						// this.unifiedorderPay()
						if (this.payWay == '') {
							uni.showToast({
								title: '请选择支付方式'
							})
							return;
						}
						if (this.payWay == 'B') {
							if (this.paymentList.order_amount <= this.paymentList.user_amount) {
								this.payAmountOrderAmountPay()
							} else {
								uni.showToast({
									title: '余额不足'
								})
								return;
							}

						} else if (this.payWay == 'C') {
							// 月结
							api.get({
								url: 'Order/GetOrderMonthlyPay',
								data: {
									order_no: this.order.order_no
								},
								success: data => {
									console.info('payMWX:' + JSON.stringify(data))
									if (data.ErrCode == 0) {
										this.isShowPop = true
									} else {
										uni.showToast({
											title: data.ErrMsg,
											icon: 'non'
										})
									}

								},

							});
						} else if (this.payWay == 'D') {
							// 货到付款
							api.get({
								url: 'Order/GetOrderCasePay',
								data: {
									order_no: this.order.order_no
								},
								success: data => {
									console.info('payMWX:' + JSON.stringify(data))
									if (data.ErrCode == 0) {
										this.isShowPop = true
									} else {
										uni.showToast({
											title: data.ErrMsg,
											icon: 'non'
										})
									}

								},

							});
						} else {
							// this.payMWx()
							this.payWx()
							// this.payMWxtest()
						}
					},
					close() {
						this.isShowPop = false
					},
					RadioChange(e) {
						console.log(JSON.stringify(e.detail.value))
						this.payWay = e.detail.value
					},
				}
			}
</script>

<style lang="scss" scoped>
	.close {
		font-size: 40upx;
		position: absolute;
		right: 20upx;
		top: 20upx;
	}

	.popup-btn>view:nth-child(1) {
		width: 220upx;
		height: 62upx;
		background-color: #ffffff;
		border-radius: 31upx;
		border: solid 1upx #cccccc;
		text-align: center;
		line-height: 62upx;
		font-size: 26upx;
		color: #666666;
	}

	.popup-btn>view {
		margin-top: 40upx;
	}

	.popup-btn>view:nth-child(2) {
		width: 240upx;
		height: 62upx;
		background-color: $btn-bground;
		border-radius: 31upx;
		text-align: center;
		line-height: 62upx;
		font-size: 26upx;
		color: #ffffff;
		margin-left: 18upx;
	}

	.popup-con image {
		width: 79upx;
		height: 98upx;
	}

	.popup-con>text:nth-child(2) {
		font-size: 32upx;
		color: #d9b94b;
		margin-top: 16upx;
		margin-bottom: 16upx;
	}

	.popup-con>text:nth-child(3),
	.popup-con>text:nth-child(4) {
		font-size: 24upx;
		color: #666666;
	}

	.popup-con {
		position: relative;
		width: 580upx;
		height: 432upx;
		background-color: #ffffff;
		border-radius: 6upx;
	}

	.popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.3);
	}

	.botbtn view,
	.botbtn button {
		width: 400upx;
		height: 74upx;
		background-color: $btn-bground;
		border-radius: 37upx;
		text-align: center;
		line-height: 74upx;
		color: #fff;
		font-size: 30upx;
		margin-top: 55upx;
	}

	.list {
		padding: 0 20upx;
		width: 100%;
		background-color: #fff;
		height: 92upx;
		border-bottom: 1upx solid #ddd;
	}

	.list image {
		margin-right: 20upx;
		width: 34upx;
		height: 34upx;
	}

	.list>view>text {
		font-size: 28upx;
		color: #000000;
	}

	.title {
		width: 100%;
		height: 80upx;
		padding-left: 20upx;
		font-size: 26upx;
		color: #666666;
	}

	.top text:nth-child(1) {
		font-size: 26upx;
		color: #666666;
		width: 120upx;
	}

	.top text:nth-child(2) {
		width: 120upx;
		font-size: 36upx;
		color: $btn-bground;
		margin-top: 10upx;
	}

	.top {
		width: 100%;
		height: 200upx;
		background-color: #ffffff;
	}
</style>